class V1::Homes < Grape::API
  format :json
  default_format :json

  desc '维修售后服务'
  resources :homes do
    desc '提交维修订单'
    params do
      optional :flag, type: String, desc: 'IOS不传，Android传1'
      requires :data, type: String, desc: 'JSON数据'
      optional :manager_pic, type: File, desc: '服务主管签名图片'
      optional :staff_pic, type: File, desc: '服务人员签名图片'
      optional :customer_pic, type: File, desc: '客户签收签名图片'
    end
    post :create_order do
      json_data = JSON.parse(params[:data])

      if params[:flag].present?
        if params[:flag] == '1'
          order_data = JSON.parse(json_data['order_data'])
          server_time_data = JSON.parse(json_data['server_time_data'])
          if json_data['component_data'] != ''
            component_data = JSON.parse(json_data['component_data'])
          end
        end
      else
        order_data = json_data['order_data']
        server_time_data = json_data['server_time_data']
        if json_data['component_data'] != []
          component_data = json_data['component_data']
        end
      end

      root = 'leero.cqitca.com:3001/'
      ActiveRecord::Base.transaction do
        @order = Order.find_by_id(order_data['id'])
        if params[:manager_pic].present?
          @manager_pic = Attachment.create avatar:params[:manager_pic]
          @staff_pic = Attachment.create avatar:params[:staff_pic]
          @customer_pic = Attachment.create avatar:params[:customer_pic]
        end
        @order.update sr: order_data['sr'], name: order_data['name'], phone: order_data['phone'], order_date: DateTime.parse(order_data['order_date']).strftime('%Y-%m-%d %T'),
                                     machine_type: order_data['machine_type'], machine_num: order_data['machine_num'], machine_time: order_data['machine_time'],
                                     machine_date: DateTime.parse(order_data['machine_date']).strftime('%Y-%m-%d %T'), service_type: order_data['service_type'],
                                     is_in_release: order_data['is_in_release'], trouble: order_data['trouble'], content: order_data['content'], trouble_num: order_data['trouble_num'],
                                     signed_num: order_data['signed_num'], packing_num: order_data['packing_num'], advise: order_data['advise'], sales_service_cost: order_data['sales_service_cost'],
                                     component_cost: order_data['component_cost'], service_cost: order_data['service_cost'], total_price: order_data['total_price'], last_address: order_data['last_address'],
                                     manager_pic: @manager_pic.present? ? root + @manager_pic.avatar.url : '', staff_pic: @staff_pic.present? ? root + @staff_pic.avatar.url : '',
                                     customer_pic: @customer_pic.present? ? root + @customer_pic.avatar.url : '', user_id: order_data['user_id'] , status:1

        server_time_data.each do |each_server|
          @order_date = OrderDate.create order_id:@order.id , starttime:DateTime.parse(each_server['starttime']).strftime('%Y-%m-%d %T'),
                                         endtime:DateTime.parse(each_server['endtime']).strftime('%Y-%m-%d %T'),totaltime:(each_server['endtime'].to_f - each_server['starttime'].to_f)
        end

        if component_data.present?
          component_data.each do |each_component|
            @order_component = OrderComponent.create order_id:@order.id , material_num:each_component['material_num'],
                                                     material_name:each_component['material_name'] ,amount:each_component['amount'],price:each_component['price']
          end
        end

        gps_list = Gp.where(user_id: order_data['user_id'], order_id: 1)
        gps_list.each do |each_gps|
          each_gps.update(order_id: @order.id)
        end

        {message: 'success', state: true}
      end
    end

    # desc '创建维修售后订单(安卓)'
    # params do
    #   requires :sr, type: String, desc: '服务单号'
    #   requires :name, type: String, desc: '客户名称'
    #   requires :phone, type: String, desc: '客户电话'
    #   requires :order_date, type: String, desc: '填表日期'
    #   requires :machine_type, type: String, desc: '机器机种'
    #   requires :machine_num, type: String, desc: '机器机号'
    #   requires :machine_time, type: String, desc: '机台运转时间'
    #   requires :machine_date, type: String, desc: '出厂日期'
    #   requires :service_type, type: String, desc: '服务类型'
    #   requires :is_in_release, type: Integer, desc: '是否过保固期'
    #   requires :trouble, type: String, desc: '故障现象'
    #   requires :content, type: String, desc: '服务内容'
    #   requires :trouble_num, type: String, desc: '故障原因代号'
    #   requires :signed_num, type: String, desc: '签定单号'
    #   requires :packing_num, type: String, desc: '出货单号'
    #   requires :advise, type: String, desc: '分析与建议'
    #   requires :sales_service_cost, type: Float, desc: '售服成本'
    #   requires :component_cost, type: Float, desc: '零件费用'
    #   requires :service_cost, type: Float, desc: '服务费用'
    #   requires :total_price, type: Float, desc: '总价'
    #   optional :manager_pic, type: File, desc: '服务主管签名图片'
    #   optional :staff_pic, type: File, desc: '服务人员签名图片'
    #   optional :customer_pic, type: File, desc: '客户签收签名图片'
    #   requires :last_address, type: String, desc: '最后一次GPS位置'
    #
    # end
    # post :create_order do
    #   if params[:manager_pic].present?
    #     @manager_pic = Attachment.create avatar:params[:manager_pic]
    #     @staff_pic = Attachment.create avatar:params[:staff_pic]
    #     @customer_pic = Attachment.create avatar:params[:customer_pic]
    #   end
    #
    #
    #   @order = Order.create sr: params[:sr], name: params[:name], phone: params[:phone], order_date: DateTime.parse(params[:order_date]).strftime('%Y-%m-%d %T'),
    #                                machine_type: params[:machine_type], machine_num: params[:machine_num], machine_time: params[:machine_time],
    #                                machine_date: DateTime.parse(params[:machine_date]).strftime('%Y-%m-%d %T'), service_type: params[:service_type],
    #                                is_in_release: params[:is_in_release], trouble: params[:trouble], content: params[:content], trouble_num: params[:trouble_num],
    #                                signed_num: params[:signed_num], packing_num: params[:packing_num], advise: params[:advise], sales_service_cost: params[:sales_service_cost],
    #                                component_cost: params[:component_cost], service_cost: params[:service_cost], total_price: params[:total_price], last_address: params[:last_address],
    #                                manager_pic: @manager_pic.avatar.url, staff_pic: @staff_pic.avatar.url, customer_pic: @customer_pic.avatar.url
    #
    #   if @order
    #     @gps = Gp.where(order_id:1)
    #     @gps.each do |item|
    #       item.update_attributes(order_id:@order.id)
    #     end
    #     {id:@order.id}
    #   else
    #     {message: 'error'}
    #   end
    # end
    #
    desc '创建维修售后订单(IOS版)'
    params do
      requires :sr, type: String, desc: '服务单号'
      requires :name, type: String, desc: '客户名称'
      requires :phone, type: String, desc: '客户电话'
      requires :order_date, type: String, desc: '填表日期'
      requires :machine_type, type: String, desc: '机器机种'
      requires :machine_num, type: String, desc: '机器机号'
      requires :machine_time, type: String, desc: '机台运转时间'
      requires :machine_date, type: String, desc: '出厂日期'
      requires :service_type, type: String, desc: '服务类型'
      requires :is_in_release, type: Integer, desc: '是否过保固期'
      requires :trouble, type: String, desc: '故障现象'
      requires :content, type: String, desc: '服务内容'
      requires :trouble_num, type: String, desc: '故障原因代号'
      requires :signed_num, type: String, desc: '签定单号'
      requires :packing_num, type: String, desc: '出货单号'
      requires :advise, type: String, desc: '分析与建议'
      requires :sales_service_cost, type: Float, desc: '售服成本'
      requires :component_cost, type: Float, desc: '零件费用'
      requires :service_cost, type: Float, desc: '服务费用'
      requires :total_price, type: Float, desc: '总价'
      requires :last_address, type: String, desc: '最后一次GPS位置'

    end
    post :create_order_for_ios do
      if params[:manager_pic].present?
        @manager_pic = Attachment.create avatar:params[:manager_pic]
        @staff_pic = Attachment.create avatar:params[:staff_pic]
        @customer_pic = Attachment.create avatar:params[:customer_pic]
      end


      @order = Order.create sr: params[:sr], name: params[:name], phone: params[:phone], order_date: DateTime.parse(params[:order_date]).strftime('%Y-%m-%d %T'),
                                  machine_type: params[:machine_type], machine_num: params[:machine_num], machine_time: params[:machine_time],
                                  machine_date: DateTime.parse(params[:machine_date]).strftime('%Y-%m-%d %T'), service_type: params[:service_type],
                                  is_in_release: params[:is_in_release], trouble: params[:trouble], content: params[:content], trouble_num: params[:trouble_num],
                                  signed_num: params[:signed_num], packing_num: params[:packing_num], advise: params[:advise], sales_service_cost: params[:sales_service_cost],
                                  component_cost: params[:component_cost], service_cost: params[:service_cost],
                                  total_price: params[:total_price], last_address: params[:last_address]


      if @order
        @gps = Gp.where(order_id:1)
        @gps.each do |item|
          item.update_attributes(order_id:@order.id)
        end
        {id:@order.id}
      else
        {message: 'error'}
      end
    end


    desc '保存IOS图片地址'
    params do
      requires :order_id, type: Integer,desc: '订单ID'
    end

    post :create_order_pic do
      route_url = 'http://o97lekzm9.bkt.clouddn.com/'
      @order = Order.find_by_id(params[:order_id])
      if @order.present?
        @order.update_attributes(manager_pic: route_url + params[:order_id].to_s + '_manager_pic',
                                 staff_pic: route_url + params[:order_id].to_s + '_staff_pic',
                                 customer_pic: route_url + params[:order_id].to_s + '_customer_pic')
        {message:'success'}
      else
        {message:'error'}
      end
    end



    desc '创建服务时间'
    params do
      requires :order_id, type: Integer, desc: '订单ID'
      requires :starttime, type: String, desc: '开始时间'
      requires :endtime, type: String, desc: '结束时间'
    end

    post :create_order_time do
        @order_date = OrderDate.create order_id:params[:order_id] , starttime:DateTime.parse(params[:starttime]).strftime('%Y-%m-%d %T'),
                                       endtime:DateTime.parse(params[:endtime]).strftime('%Y-%m-%d %T'),totaltime:(params[:endtime].to_f - params[:starttime].to_f)
      if @order_date
        {message:'created'}
      else
        {message:'error'}
      end
    end

    desc '创建订单服务更换零件'
    params do
      requires :order_id, type: Integer, desc: '订单ID'
      requires :material_num, type: Integer, desc: '料号'
      requires :material_name, type: String, desc: '品名'
      requires :amount, type: Integer, desc: '数量'
      requires :price, type: Float, desc: '金额'
    end

    post :create_order_component do
      @order_component = OrderComponent.create order_id:params[:order_id] , material_num:params[:material_num],
                         material_name:params[:material_name] ,amount:params[:amount],price:params[:price]
      if @order_component
        {message:'created'}
      else
        {message:'error'}
      end
    end


    desc '发送GPS信息'
    params do
      requires :order_id ,type: Integer, desc:'订单ID'
      requires :longitude, type: String, desc:'经度位置'
      requires :latitude , type: String, desc:'维度位置'
      requires :recording_time, type: String, desc:'记录时间'
      requires :user_id, type: String, desc: '维修员id'
    end
    post :create_gps do
      @gps = Gp.create order_id: params[:order_id] ,  longitude: params[:longitude] , latitude:params[:latitude],
          recording_time: DateTime.parse(params[:recording_time]).strftime('%Y-%m-%d %T'), user_id: params[:user_id]
      if @gps
        {message:'created'}
      else
        {message:'error'}
      end
    end

    desc '获取所有未派送订单'
    get :get_all_orders do
      @orders = Order.where(status: 0)
      if @orders.present?
        @orders
      else
        {}
      end
    end

    desc '获取对应职工已派送订单'
    params do
      requires :user_id, type: Integer, desc: '职工id'
    end
    post :get_complete_orders do
      @orders = Order.where(user_id: params[:user_id], status: 1)
      if @orders.present?
        @orders
      else
        {}
      end
    end

    desc '获取单个订单'
    params do
      requires :id , type: Integer,desc:'订单ID'
    end
    get :get_order do
      @order = Order.find_by_id(params[:id])
      @dates = OrderDate.where('order_id=?',params[:id])
      @components = OrderComponent.where('order_id=?',params[:id])
      if @order.present?
        @order
      else
        {}
      end
    end

    desc '获取单个订单服务时间'
    params do
      requires :id , type: Integer,desc:'订单ID'
    end
    get :get_order_dates do
      @order = Order.find_by_id(params[:id])
      @dates = OrderDate.where('order_id=?',params[:id])
      if @order.present?
        @dates
      else
        {}
      end
    end

    desc '获取单个订单零件'
    params do
      requires :id , type: Integer,desc:'订单ID'
    end
    get :get_order_components do
      @order = Order.find_by_id(params[:id])
      @components = OrderComponent.where('order_id=?',params[:id])
      if @order.present?
        @components
      else
        {}
      end
    end

    desc '测试附件上传'
    params do
      requires :file ,type: File, desc:'附件'
    end

    post :create_file do
      @attachment = Attachment.new avatar:params[:file]
      if @attachment.save
        {attachment:@attachment}
      else
        {message:'error'}
      end
    end

    desc '通过订单信息获取GPS'
    params do
      requires :id ,type: Integer, desc:'订单id'
    end

    get :get_gps do
      # 查找到固定id的订单
      @order = Order.find_by_id(params[:id])
      if @order
        # 通过时间排序获取gps信息
        @gps = Gp.where(order_id:@order.id).order(created_at: :asc)
        if @gps.present?
          # gps信息加入数组(便于前端获取)
          gps = []
          @gps.each do |item|
            gps << [item.longitude,item.latitude]
          end
          # 返回信息加入起始和结束地址
          {gps:gps,
           center_add:[(@gps.first.longitude.to_f + @gps.last.longitude.to_f)/2,
                   (@gps.first.latitude.to_f + @gps.last.latitude.to_f)/2],
           first_add:[@gps.first.longitude,@gps.first.latitude],
           last_add:[@gps.last.longitude,@gps.last.latitude]
          }
        else
        end

      else
        {message:'error'}
      end
    end

    desc '获取最新GPS'
    params do
      requires :user_id , type:Integer
    end

    get :get_latest_gps do
        gps = []
        # 获取最新gps信息
        @gps_last = Gp.where(user_id:params[:user_id]).last
        if Gp.count > 10
          @gps_center = Gp.where(user_id:params[:user_id]).last(10).first
          count = 10
        else
          @gps_center = Gp.where(user_id:params[:user_id]).last(5).first
          count = 5
        end

        # gps信息加入数组(便于前端获取)
        Gp.where(user_id:params[:user_id]).last(count).each do |item|
          gps << [item.longitude,item.latitude]
        end

        if @gps_last.present?
          # 返回信息加入起始和结束地址
          {gps_arr:gps,
           lastest_add:[@gps_last.longitude,@gps_last.latitude],
            center_add:[@gps_center.longitude,@gps_center.latitude]
          }
        else
        end
    end

    desc '测试七牛'
    get :get_token do
      # 构建鉴权对象
      Qiniu.establish_connection! :access_key => 'xYW4B_Yxpvxbb0TcXRFxoG7HajlkImM8pnmUsgzc',
                                  :secret_key => 'xuCYak_Gy-QlAxXJts8kz2VHak_OkAi4f-05fWDH'

      #要上传的空间
      bucket = 'picture'

      #构建上传策略
      put_policy = Qiniu::Auth::PutPolicy.new(
          bucket,      # 存储空间
          nil,     # 最终资源名，可省略，即缺省为“创建”语义，设置为nil为普通上传
          3600    #token过期时间，默认为3600s
      )

      #生成上传 Token
      uptoken = Qiniu::Auth.generate_uptoken(put_policy)

      #打印上传返回的信息
      puts uptoken
      if uptoken.length > 0
        {uptoken:uptoken}
      else
      end
    end

    desc '登录'
    params do
      requires :account, type: String, desc: '职工号'
      requires :password, type: String, desc: '密码'
    end
    post :login do
      user = User.find_by_employee_number(params[:account])
      return {message: '不存在该用户', state: false} if user.nil?
      if user.valid_password? params[:password]
        sign_in user
        {message: '登录成功', state: true, user_id: user.id}
      else
        {message: '密码错误', state: false}
      end
    end

    desc '注册'
    params do
      requires :account, type: String, desc: '职工号'
      requires :password, type: String, desc: '密码（8位或以上）'
    end
    post :register do
      if User.find_by_employee_number(params[:account]).present?
        {message: '用户已存在', state: true}
      else
        user = User.new({employee_number: params[:account], password: params[:password], password_confirmation: params[:password]})
        if user.save
          sign_in user
          {state: true, message: '注册成功'}
        else
          {state: false, message: '注册失败，数据保存出错'}
        end
      end
    end

  end
end